﻿using BAL;
using DAL;
using DAL.DataProvider;
using DAL.DataTransferObject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Module.QLKhachHang
{
    public partial class frmQLKhachHang : Form
    {
        public KhachHangBAO khBAO = new KhachHangBAO();
        public frmQLKhachHang()
        {
            InitializeComponent();
        }
        public void loadData()
        {
            dv = khBAO.SelectViewAllKhachHang();
            List<KhachHang> listKH = khBAO.KhachHang_GetData();
            DGV.DataSource = listKH;
            for (int i = 0; i < DGV.Rows.Count; i++)
            {
                DGV.Rows[i].Cells[0].Value = (i + 1);
            }

            SqlCommand cmd = new SqlCommand("select max(MaKh) as MaxKH from KhachHang where MaKh not like 'KHx%'", DataAccess.GetConnection());
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            sda.Fill(table);
            int newInx = Convert.ToInt32(table.Rows[0]["MaxKH"].ToString().Substring(2, 4)) + 1;
            string newIndexStr = newInx.ToString();
            while (newIndexStr.Length < 4)
                newIndexStr = "0" + newIndexStr;
            newIndexStr = "KH" + newIndexStr;
            txtMaKH.Text = newIndexStr;
        }

        Timer timer = new Timer();
        private void frmKhachHang_Load(object sender, EventArgs e)
        {
            loadData();
            DGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            bt_update.Enabled = false;
            btDelete.Enabled = false;
            for (int i = 0; i < DGV.Rows.Count; i++)
            {
                DGV.Rows[i].Cells[0].Value = (i + 1);
            }
            timer.Interval = 1000;
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            btReset.PerformClick();
            timer.Stop();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtMaKH.Text.Length == 0) throw new Exception("Mã Khách Hàng không được bỏ trống"); txtMaKH.Focus();
                if (txtHoDem.Text.Length == 0) throw new Exception("Họ Đệm khách hàng không được bỏ trống"); txtHoDem.Focus();
                if (txtTen.Text.Length == 0) throw new Exception("Tên khách hàng không được bỏ trống"); txtTen.Focus();
                if (txtDiaChi.Text.Length == 0) throw new Exception("Địa chỉ khách hàng không được bỏ trống"); txtDiaChi.Focus();
                if (txtMST.Text.Length == 0) throw new Exception("Mã số thuế khách hàng không được bỏ trống"); txtMST.Focus();
                if (txtCMND.Text.Length == 0) throw new Exception("CMND khách hàng không được bỏ trống"); txtCMND.Focus();
                KhachHang kh = new KhachHang();
                getInfo(kh);
                khBAO.KhachHang_AddNew(kh);
                loadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR");
            }
        }
        public void getInfo(KhachHang kh)
        {

            kh.maKhachHang = txtMaKH.Text;
            kh.hoDemKH = txtHoDem.Text;
            kh.tenKH = txtTen.Text;
            kh.SDT = txtSDT.Text;
            kh.diaChi = txtDiaChi.Text;
            kh.gioiTinh = CboGT.Text;
            kh.maSoThue = txtMST.Text;
            kh.ngaySinh = dtNgaySinh.Value;
            kh.CMND = txtCMND.Text;
            kh.ghiChu = txtGhiChu.Text;
            kh.loaiKH = cboLoaiKH.Text; ;

        }

        private void bt_update_Click(object sender, EventArgs e)
        {

            KhachHang kh = new KhachHang();
            getInfo(kh);
            khBAO.KhachHang_Update(kh);
            loadData();
            Reset();
        }

        private void DGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (SearchClicked)
            {
                DataView dv = new DataView();
                dv = khBAO.SelectViewAllKhachHang();
                string key = DGV.SelectedRows[0].Cells[1].Value.ToString();
                int rowIndex = AutoGenCode.GetRealIndexOfRow(key, dv, 0);
                btsearch.PerformClick();
                DGV.ClearSelection();
                DGV.CurrentRow.Selected = false;
                DGV.CurrentCell = DGV[0, rowIndex];
            }

            DataGridViewRowToControls();
        }


        public void DataGridViewRowToControls()
        {
            txtMaKH.Text = Convert.ToString(DGV.CurrentRow.Cells[1].Value);
            txtCMND.Text = Convert.ToString(DGV.CurrentRow.Cells[2].Value);
            txtHoDem.Text = Convert.ToString(DGV.CurrentRow.Cells[3].Value);
            txtTen.Text = Convert.ToString(DGV.CurrentRow.Cells[4].Value);
            txtDiaChi.Text = Convert.ToString(DGV.CurrentRow.Cells[5].Value);
            txtSDT.Text = Convert.ToString(DGV.CurrentRow.Cells[6].Value);
            dtNgaySinh.Value = Convert.ToDateTime(DGV.CurrentRow.Cells[7].Value);
            CboGT.Text = Convert.ToString(DGV.CurrentRow.Cells[8].Value);
            txtMST.Text = Convert.ToString(DGV.CurrentRow.Cells[9].Value);
            cboLoaiKH.Text = Convert.ToString(DGV.CurrentRow.Cells[10].Value);
            txtGhiChu.Text = Convert.ToString(DGV.CurrentRow.Cells[11].Value);

            txtMaKH.Enabled = false;
            txtHoDem.Enabled = false;
            txtTen.Enabled = false;
            dtNgaySinh.Enabled = false;
            CboGT.Enabled = false;
            txtMST.Enabled = false;
            bt_addNew.Enabled = false;
            txtCMND.Enabled = false;
            bt_update.Enabled = true;
            btDelete.Enabled = true;
            txtDiaChi.Enabled = true;
            txtSDT.Enabled = true;
            cboLoaiKH.Enabled = true;
            txtGhiChu.ReadOnly = true;
            //btsearch.Enabled = false;
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            KhachHang kh = new KhachHang();
            getInfo(kh);
            kh.ghiChu = "NO";
            khBAO.KhachHang_Update(kh);
            loadData();
            Reset();
        }

        bool SearchClicked = false;
        private void btsearch_Click(object sender, EventArgs e)
        {
            if (!SearchClicked)
            {
                SearchClicked = true;
                Reset();
                btsearch.BackgroundImage = (Image)(Moduel.QLKhachHang.Properties.Resources.ResourceManager.GetObject("TatTK"));
                SearchMode(true);
                txtMaKH.Text = txtGhiChu.Text = "";
                txtGhiChu.ReadOnly = false;
                lblKT.Visible = dtKT.Visible = true;
                cboLoaiKH.Items.Add("Tat ca");
                CboGT.Items.Add("Tat ca");
                for (int i = 0; i < DGV.Rows.Count; i++)
                {
                    DGV.Rows[i].Cells[0].Value = (i + 1);
                }
                dtKT.Value = dtKT.MaxDate;
                dtNgaySinh.Value = dtNgaySinh.MinDate;
            }
            else
            {
                lblKT.Visible = dtKT.Visible = false;
                SearchClicked = false;
                btsearch.BackgroundImage = (Image)(Moduel.QLKhachHang.Properties.Resources.ResourceManager.GetObject("BatTK"));
                Reset();
                btReset.Enabled = true;
                btReset.PerformClick();
                loadData();
                cboLoaiKH.Items.Remove("Tat ca");
                CboGT.Items.Remove("Tat ca");
                //dtNgaySinh.Value = DateTime.Now;
            }
        }

        public void SearchMode(bool logic)
        {
            txtMaKH.ReadOnly = !logic;
            txtHoDem.Enabled = logic;
            txtTen.Enabled = logic;
            dtNgaySinh.Enabled = logic;
            CboGT.Enabled = logic;
            txtMST.Enabled = logic;
            txtCMND.Enabled = logic;
            txtDiaChi.Enabled = logic;
            txtSDT.Enabled = logic;
            cboLoaiKH.Enabled = logic;
            txtGhiChu.Enabled = logic;


            bt_addNew.Enabled = !logic;
            bt_update.Enabled = !logic;
            btDelete.Enabled = !logic;
        }

        private void txtsearch_Click(object sender, EventArgs e)
        {
            txtMaKH.Enabled = false;
            txtHoDem.Enabled = false;
            txtTen.Enabled = false;
            dtNgaySinh.Enabled = false;
            CboGT.Enabled = false;
            txtMST.Enabled = false;
            bt_addNew.Enabled = false;
            txtCMND.Enabled = false;
            txtDiaChi.Enabled = false;
            txtGhiChu.Enabled = false;
            txtSDT.Enabled = false;
            cboLoaiKH.Enabled = false;
            bt_update.Enabled = false;
            btDelete.Enabled = false;
        }

        private void btReset_Click(object sender, EventArgs e)
        {
            Reset();
            txtMaKH.ReadOnly = true;
        }
        public void Reset()
        {
            txtMaKH.Enabled = true;
            txtHoDem.Enabled = true;
            txtTen.Enabled = true;
            dtNgaySinh.Enabled = true;
            CboGT.Enabled = true;
            txtMST.Enabled = true;
            bt_addNew.Enabled = true;
            txtCMND.Enabled = true;
            txtDiaChi.Enabled = true;
            txtGhiChu.Enabled = true;
            txtSDT.Enabled = true;
            cboLoaiKH.Enabled = true;
            bt_update.Enabled = false;
            btDelete.Enabled = false;
            txtMaKH.Clear();
            txtHoDem.Clear();
            txtTen.Clear();
            txtCMND.Clear();
            txtDiaChi.Clear();
            txtGhiChu.Text = "YES";
            txtMST.Clear();
            txtSDT.Clear();
            CboGT.Text = "";
            cboLoaiKH.Text = "";
            dtNgaySinh.Value = DateTime.Now;
            btsearch.Enabled = true;
            loadData();
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        DataView dv = new DataView();
        List<string> listStringFilter = new List<string>();

        private string ToStringFilter(List<string> list)
        {
            Console.WriteLine(list.Count.ToString());
            string s = "";
            if (list.Count >= 2)
                for (int i = 0; i < list.Count - 1; i++)
                    s += list.ToArray()[i] + " AND ";
            s += list.ToArray()[list.Count - 1];
            return s;
        }

        private void FilterChanged(object sender, EventArgs e)
        {
            if (SearchClicked)
            {
                //MessageBox.Show("Text changed");
                listStringFilter = new List<string>();

                listStringFilter.Add(String.Format(" SoCMND like '{0}%'", txtCMND.Text));
                listStringFilter.Add(String.Format(" DiaChi like '{0}%'", txtDiaChi.Text));
                listStringFilter.Add(String.Format(" GhiChu like '{0}%'", txtGhiChu.Text));
                listStringFilter.Add(String.Format(" HoDemKH like '{0}%'", txtHoDem.Text));
                listStringFilter.Add(String.Format(" MaKH like '{0}%'", txtMaKH.Text));
                listStringFilter.Add(String.Format(" MST like '{0}%'", txtMST.Text));
                listStringFilter.Add(String.Format(" SDT like '{0}%'", txtSDT.Text));
                listStringFilter.Add(String.Format(" TenKH like '{0}%'", txtTen.Text));

                listStringFilter.Add(String.Format("(NgaySinh >= '{0}' and NgaySinh <= '{1}')", dtNgaySinh.Value, dtKT.Value));

                if (CboGT.Text != "Tat ca")
                    listStringFilter.Add(String.Format("GioiTinh like '{0}%'", CboGT.Text));
                else
                    listStringFilter.Add(String.Format("GioiTinh like '%'", CboGT.Text));
                if (cboLoaiKH.Text != "Tat ca")
                    listStringFilter.Add(String.Format("LoaiKH like '{0}%'", cboLoaiKH.Text));
                else
                    listStringFilter.Add(String.Format("LoaiKH like '%'", cboLoaiKH.Text));



                dv.RowFilter = ToStringFilter(listStringFilter);
                DGV.DataSource = dv;
            }
        }

    }
}
